package com.endurance.compoent;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

@Component
public class TransactionManager {

    @Autowired
    ConnectionFactory connectionFactory;

    @Autowired
    ThreadLocal threadLocal;

    /**
     * 开启事务
     */
    public void beginTransaction() {
        try {
            connectionFactory.currentThreadConn().setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 提交事务
     */
    public void commit() {
        try {
            connectionFactory.currentThreadConn().commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 回滚事务
     */
    public void rollback() {
        try {
            connectionFactory.currentThreadConn().rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void release() {
        try {
            // 关闭当前数据库连接
            connectionFactory.currentThreadConn().close();
            // 将数据库连接与当前线程解绑, 解绑后该连接可以与其他线程绑定.
            threadLocal.remove();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
